package cn.xerllent.wxtp.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.xerllent.wxtp.entity.DksbCourse;
import cn.xerllent.wxtp.entity.WxReport;
import cn.xerllent.wxtp.service.DksbCourseService;
import cn.xerllent.wxtp.service.DksbReportService;
import cn.xerllent.wxtp.service.dto.DksbFilter;
import cn.xerllent.wxtp.utils.DksbConsts;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class DksbReportServiceImpl extends WxReportServiceImpl implements DksbReportService {

	@Resource
	private DksbCourseService dksbCourseService;

	/**
	 * 根据参数生成报表
	 *  1生成报表文件
	 *  2上传媒体
	 *  3执行id转译
	 *  4等待回调
	 * */
	@Override
	public void createReport(WxReport resource, WxCpTpService tpService) {
		BigExcelWriter writer =null;
		try {
			//1生成报表文件:sheet1-代课明细
			List<DksbCourse>  all = dksbCourseService.queryAll(DksbFilter.fromJson(resource.getParams()));

			List<Map<String, Object>> list = new ArrayList<>();//代课明细
			Map<String, BigDecimal[]> totalMap = new LinkedHashMap<String, BigDecimal[]>(); //教师代课汇总
			
			for (DksbCourse Dksb : all) {
				//明细
			    Map<String, Object> map = new LinkedHashMap<>();
			    map.put("id", Dksb.getId());
			    map.put("申报id", Dksb.getDksbId());
			    map.put("被代课教师", "$userName="+Dksb.getSrcUserid()+"$");
			    map.put("代课教师", "$userName="+Dksb.getTarUserid()+"$");
			    map.put("代课日期", Dksb.getEventdate().toString());
			    map.put("年级", DksbConsts.gradeMap.get(Dksb.getGrade()));
			    map.put("班级", DksbConsts.claszMap.get(Dksb.getClasz()));
			    map.put("学科", DksbConsts.subjectMap.get(Dksb.getSubject()));
			    map.put("节次", DksbConsts.coursetimeMap.get(Dksb.getCoursetime()));
			    map.put("课时数", Dksb.getHours());
			    list.add(map);
			    
			    //汇总计算
			    //代课教师
			    BigDecimal[] d1 = totalMap.get(Dksb.getTarUserid());
			    if(Objects.isNull(d1)) {
			    	d1=new BigDecimal[]{new BigDecimal(0),new BigDecimal(0)}; //[代课数,被代课数]
			    	totalMap.put(Dksb.getTarUserid(), d1);
			    }
			    d1[0]=d1[0].add(Dksb.getHours());
			    
			    //被代教师
			    BigDecimal[] d2 = totalMap.get(Dksb.getSrcUserid());
			    if(Objects.isNull(d2)) {
			    	d2=new BigDecimal[]{new BigDecimal(0),new BigDecimal(0)}; //[代课数,被代课数]
			    	totalMap.put(Dksb.getSrcUserid(), d2);
			    }		    
			    d2[1]=d2[1].add(Dksb.getHours());
			    
			}

			String filename = IdUtil.fastSimpleUUID() + ".xlsx";
			String filePath = getReportPath() +File.separator + filename;
			File file = new File(filePath);
			writer = ExcelUtil.getBigWriter(file,"代课明细");
			// 一次性写出内容，使用默认样式，强制输出标题
			writer.write(list, true);
			writer.autoSizeColumnAll();
			
			//2生成报表文件:sheet2-教师代课汇总，按教师分类汇总
			writer.setSheet("教师代课汇总");
			
			List<Map<String, Object>> list2= totalMap.entrySet().stream().map(entry->{
				String id = entry.getKey();
				BigDecimal[] d = entry.getValue();
			    Map<String, Object> map = new LinkedHashMap<>();
			    map.put("教师", "$userName="+id+"$");
			    map.put("代课时数", d[0]);
			    map.put("被代课时数", d[1]);
			    map.put("总代课时数", d[0].subtract(d[1]));
			    return map;
			}).collect(Collectors.toList());
			writer.write(list2, true);
			writer.autoSizeColumnAll();
			
			writer.flush();

			resource.setFilepath(filename).setStatus(1);
			saveOrUpdate(resource);
		} catch (Exception e) {
			saveOrUpdate(resource.setStatus(-1));
			if (writer != null) {
				writer.close(); // 关闭文件资源
			}
			return;
		}

		doIdTranslate(resource,tpService);

	}




}
